import React, { Fragment, useState } from 'react';
import { Button, Col, Form, Row, Card, Empty } from 'antd';
import { connect } from 'umi';
import { eventTrack } from '@/utils/track';
import { history } from 'umi';
import moment from 'moment';
import { Link }  from 'umi';
// import { history } from 'umi';
import { QuickForm } from 'vv-frontend-components';
import cn from 'classnames';
// import request from '@/utils/request';
// import { CompanyDepart } from '@/containers';
import QueryPage from '@/components/QueryPage';
import List from '@/components/List';
import TabsList from '@/components/List/TabsList';
import Locale from '@/utils/locale';
import DateRange from '@/components/DateRange';
import updateQuery from '@/utils/formValuesToQuery';
// import { exists } from '@/utils/utils';
import LinkTo from '@/components/LinkTo';
import { withRoutePage } from '@/utils/enhanceUtils';
import OrganizationSelect from '@/components/OrganizationSelect';
import KqlxYc from './KqlxYc';
import JblxFx from './JblxFx';
import QjlxFx from './QjlxFx';
import CqlFx from './CqlFx';
import styles from './index.less';

const { locale } = new Locale('stat.report');
// const { RangePicker } = DatePicker;
// const { Option } = Select;

const cqlphOption = getForm => {
    const { companyId = '', departmentId, startTime = '', endTime = '', type = '', quarter = '' } = getForm;
    return [
        {
            title: '序号',
            key: 'sort',
            render(text, record, index) {
                return (
                    <span
                        className={cn(styles.xh, {
                            [styles.orange]: index <= 2
                        })}
                    >
                        {index + 1}
                    </span>
                );
            }
        },
        {
            title: 'userName',
            dataIndex: 'userName',
            key: 'userName',
            width: 80,
            render(text, record) {
                return (
                    <Link
                        to={`/office/personnelManagement/attendance/report/reportRank?id=${record.id}&employeeName=${
                            record.userName
                        }&companyId=${companyId}&departmentId=${departmentId ||
                            ''}&dateType=${type}&startTime=${startTime}&endTime=${endTime}&quarter=${quarter}`}
                    >
                        {text}
                    </Link>
                );
            }
        },
        {
            title: '组织机构',
            dataIndex: 'departName',
            key: 'departName'
        },
        {
            title: 'position',
            dataIndex: 'position',
            key: 'position',
            width: 200
        },
        {
            title: 'continuous',
            dataIndex: 'continuous',
            key: 'continuous',
            width: 150,
            render(text) {
                return (
                    <span>
                        出勤率<span className="oa-number">{text}%</span>
                    </span>
                );
            }
        }
    ];
};

const publicColumns = (renderCommon, userNamePath = '', getForm = {}) => {
    const { companyId = '', departmentId = '', startTime = '', endTime = '', type = '', quarter = '' } = getForm;
    return [
        {
            title: '序号',
            key: 'sort',
            render(text, record, index) {
                return (
                    <span
                        className={cn(styles.xh, {
                            [styles.orange]: index <= 2
                        })}
                    >
                        {index + 1}
                    </span>
                );
            }
        },
        {
            title: 'userName',
            dataIndex: 'userName',
            key: 'userName',
            width: 80,
            render(text, record) {
                let companyKey = 'companyId';
                let departmentKey = 'departmentId';

                if (userNamePath === '/office/personnelManagement/attendance/timetag/leaveRecord') {
                    companyKey = 'companyCode';
                    departmentKey = 'departmentCode';
                }

                return userNamePath ? (
                    <Link
                        to={`${userNamePath}?id=${record.id}&employeeName=${
                            record.userName
                        }&${companyKey}=${companyId}&${departmentKey}=${departmentId ||
                            ''}&dateType=${type}&startTime=${startTime}&endTime=${endTime}&quarter=${quarter}`}
                    >
                        {text}
                    </Link>
                ) : (
                    text
                );
            }
        },
        {
            title: '组织机构',
            dataIndex: 'departName',
            key: 'departName'
        },
        {
            title: 'position',
            dataIndex: 'position',
            key: 'position'
        },
        {
            title: 'common',
            dataIndex: 'common',
            width: 80,
            key: 'common',
            render(text) {
                return text ? <span>{renderCommon(text)}</span> : text;
            }
        }
    ];
};

const Report = ({ report, loading, form, dispatch, location, match }) => {
    const {
        query: { companyId: companyIds, departmentId: departmentIds, dateType, startTime, endTime, quarter }
    } = location;
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};

    const [qjryIndex, setQjryIndex] = useState(0);
    const [jbryIndex, setJbryIndex] = useState(0);
    const [ycryIndex, setYcryIndex] = useState(0);
    const fetchData = async () => {
        const { companyId, departmentId, date = { range: [] } } = form.getFieldsValue();

        // 因为请假的tab是动态的，所以搜索时应该充值为0
        await setQjryIndex(0);
        await dispatch({
            type: 'report/fetchData',
            payload: {
                companyCode: companyId || '',
                departmentCode: departmentId || '',
                startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD') : '',
                endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD') : '',
                qjryTypeCode: '',
                ycryTypeCode: ycryIndex === 0 ? '' : ycryIndex,
                jbryTypeCode: jbryIndex === 0 ? '' : jbryIndex
            }
        });
    };
    const handleSubmit = async e => {
        const { companyId, departmentId, date = { range: [] } } = form.getFieldsValue();
        e.preventDefault();
        fetchData();

        const queryObj = {
            companyId: companyId || '',
            departmentId: departmentId || '',
            dateType: date.type,
            startTime: date.range && date.range[0] ? moment(date.range[0]).format('YYYY-MM-DD') : '',
            endTime: date.range && date.range[1] ? moment(date.range[1]).format('YYYY-MM-DD') : '',
            quarter: date?.type === 'quarter' ? date.quarter || 1 : ''
        };

        // 埋点
        await eventTrack({
            eventName: 'personnel_management_attendance_report_search_click',
            eventProps: {
                key_works: JSON.stringify(queryObj)
            }
        });

        updateQuery(match.path, queryObj);
    };

    const startFn = () =>
        moment()
            .subtract(1, 'M')
            .startOf('month');
    const endFn = () =>
        moment()
            .subtract(1, 'M')
            .endOf('month');

    const config = [
        {
            field: 'companyId',
            label: '机构',
            config: {
                initialValue: companyIds ?? user?.firstOrgInfo?.firstCompanyCode
            },
            component: <OrganizationSelect isStrictly maxTagCount={2} style={{ width: 180 }} isNeedPermission />
        },
        {
            field: 'departmentId',
            config: {
                initialValue: departmentIds ?? user?.firstOrgInfo?.firstDepartmentCode
            },
            component: (
                <OrganizationSelect
                    isFunctional
                    isStrictly
                    strictlyOutType="string"
                    maxTagCount={2}
                    style={{ width: 180 }}
                    isNeedPermission
                />
            )
        },
        {
            field: 'date',
            config: {
                initialValue: {
                    range: [
                        typeof startTime === 'undefined' ? startFn() : moment(startTime),
                        typeof endTime === 'undefined' ? endFn() : moment(endTime)
                    ],
                    type: typeof dateType === 'undefined' ? 'month' : dateType,
                    quarter: dateType === 'quarter' ? (quarter && Number(quarter)) || 1 : ''
                }
            },
            component: <DateRange allowClear={false} />
        },
        {
            component: (
                <div>
                    <Button type="primary" htmlType="submit">
                        {locale('form.search', false)}
                    </Button>
                </div>
            )
        }
    ];

    const handleQjryphChange = index => {
        const { companyId, departmentId, date = { range: [] } } = form.getFieldsValue();
        dispatch({
            type: 'report/fetchQjryph',
            payload: {
                typeCode: +index === 0 ? '' : report.qjlxfx[index - 1] && report.qjlxfx[index - 1].leaveCode,
                companyCode: companyId || '',
                departmentCode: departmentId || '',
                startTime: date.range[0] ? moment(date.range[0]).format('YYYY-MM-DD') : '',
                endTime: date.range[1] ? moment(date.range[1]).format('YYYY-MM-DD') : ''
            },
            callback: () => {
                setQjryIndex(+index);
            }
        });
    };

    const ycryChange = index => {
        const { companyId, departmentId, date = { range: [] } } = form.getFieldsValue();
        dispatch({
            type: 'report/fetchYcryph',
            payload: {
                typeCode: +index === 0 ? '' : index,
                companyCode: companyId || '',
                departmentCode: departmentId || '',
                startTime: date.range[0] ? moment(date.range[0]).format('YYYY-MM-DD') : '',
                endTime: date.range[1] ? moment(date.range[1]).format('YYYY-MM-DD') : ''
            },
            callback: () => {
                setYcryIndex(+index);
            }
        });
    };

    const jbryChange = index => {
        const { companyId, departmentId, date = { range: [] } } = form.getFieldsValue();
        dispatch({
            type: 'report/fetchJbryph',
            payload: {
                typeCode: +index === 0 ? '' : index,
                companyCode: companyId || '',
                departmentCode: departmentId || '',
                startTime: date.range[0] ? moment(date.range[0]).format('YYYY-MM-DD') : '',
                endTime: date.range[1] ? moment(date.range[1]).format('YYYY-MM-DD') : ''
            },
            callback: () => {
                setJbryIndex(+index);
            }
        });
    };

    const getForm = () => {
        const { companyId, departmentId, date = { range: [] } } = form.getFieldsValue();

        return {
            companyId: companyId || '',
            departmentId: departmentId || '',
            type: date.type,
            startTime: date.range[0] ? moment(date.range[0]).format('YYYY-MM-DD') : '',
            endTime: date.range[1] ? moment(date.range[1]).format('YYYY-MM-DD') : '',
            quarter: date?.type === 'quarter' ? date.quarter || 1 : ''
        };
    };

    React.useEffect(() => {
        fetchData();
        return () => {
            dispatch({
                type: 'report/clear'
            });
        };
    }, []);

    const { companyId, departmentId, date = { range: [] } } = form.getFieldsValue();
    return (
        <div className="reportPage">
            <QueryPage
                // style={{ overflow: 'hidden' }}
                className="queryPageSearch"
                background="transparent"
                form={
                    <Row type="flex" className="searchTitle">
                        <Col>
                            <h3>{Locale.set('form.public.title')}</h3>
                        </Col>
                        <Col>
                            <Form layout="inline" onSubmit={handleSubmit}>
                                <QuickForm form={form} config={config} />
                            </Form>
                        </Col>
                    </Row>
                }
            />
            <div className={styles.cards}>
                <Row gutter={12}>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <CqlFx data={report.cqlfx} />
                    </Col>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Card
                            bordered={false}
                            className={styles.overflowY}
                            title={locale('cqlph')}
                            extra={
                                <LinkTo
                                    // 埋点
                                    onClick={async (e, url) => {
                                        await eventTrack({
                                            eventName: 'personnel_management_attendance_report_operator_click',
                                            eventProps: {
                                                label: '考勤分析-操作-查看全部排行',
                                                tabs: locale('cqlph')
                                            }
                                        });
                                        history.push(url);
                                    }}
                                    to="/office/personnelManagement/attendance/report/reportRank"
                                    query={{
                                        key: 'attendance',
                                        companyId: companyId || '',
                                        departmentId: departmentId || '',
                                        dateType: date.type,
                                        startTime:
                                            date.range && date.range[0]
                                                ? moment(date.range[0]).format('YYYY-MM-DD')
                                                : '',
                                        endTime:
                                            date.range && date.range[1]
                                                ? moment(date.range[1]).format('YYYY-MM-DD')
                                                : '',
                                        quarter: date?.type === 'quarter' ? date.quarter || 1 : ''
                                    }}
                                >
                                    查看全部排行
                                </LinkTo>
                            }
                        >
                            {report.cqlph.length === 0 ? (
                                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            ) : (
                                <List
                                    loading={loading.effects['report/fetchCqlph']}
                                    data={report.cqlph}
                                    columns={cqlphOption(getForm())}
                                    rowKey={row => row.id}
                                />
                            )}
                        </Card>
                    </Col>
                </Row>
                <Row gutter={12}>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <QjlxFx data={report.qjlxfx} />
                    </Col>
                    <Col className={styles.relative} lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Card
                            bordered={false}
                            className={styles.tabListOverflowY}
                            title={locale('qjryph')}
                            extra={
                                <LinkTo
                                    // 埋点
                                    onClick={async (e, url) => {
                                        await eventTrack({
                                            eventName: 'personnel_management_attendance_report_operator_click',
                                            eventProps: {
                                                label: '考勤分析-操作-查看全部排行',
                                                tabs: '请假人员排行'
                                            }
                                        });
                                        history.push(url);
                                    }}
                                    to="/office/personnelManagement/attendance/report/reportRank"
                                    query={{
                                        key: 'leave',
                                        companyId: companyId || '',
                                        departmentId: departmentId || '',
                                        dateType: date.type,
                                        startTime:
                                            date.range && date.range[0]
                                                ? moment(date.range[0]).format('YYYY-MM-DD')
                                                : '',
                                        endTime:
                                            date.range && date.range[1]
                                                ? moment(date.range[1]).format('YYYY-MM-DD')
                                                : '',
                                        quarter: date?.type === 'quarter' ? date.quarter || 1 : ''
                                    }}
                                >
                                    查看全部排行
                                </LinkTo>
                            }
                        >
                            <TabsList
                                loading={loading.effects['report/fetchQjryph']}
                                className={styles.clearTabsListPadding}
                                activeKey={`${qjryIndex}`}
                                onTabChange={handleQjryphChange}
                                // title={}
                                data={[
                                    {
                                        label: '总请假',
                                        content: (
                                            <List
                                                data={report.qjryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 小时</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/timetag/leaveRecord',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    },
                                    ...report.qjlxfx.map(item => ({
                                        label: item.leaveName,
                                        content: (
                                            <List
                                                key={item.leaveCode}
                                                data={report.qjryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 小时</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/timetag/leaveRecord',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    }))
                                ]}
                            />
                        </Card>
                    </Col>
                </Row>
                <Row gutter={12}>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <JblxFx data={report.jblxfx} />
                    </Col>
                    <Col className={styles.relative} lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Card
                            bordered={false}
                            className={styles.tabListOverflowY}
                            title={locale('jbryph')}
                            extra={
                                <LinkTo
                                    // 埋点
                                    onClick={async (e, url) => {
                                        await eventTrack({
                                            eventName: 'personnel_management_attendance_report_operator_click',
                                            eventProps: {
                                                label: '考勤分析-操作-查看全部排行',
                                                tabs: '加班人员排行'
                                            }
                                        });
                                        history.push(url);
                                    }}
                                    to="/office/personnelManagement/attendance/report/reportRank"
                                    query={{
                                        key: 'overtime',
                                        companyId: companyId || '',
                                        departmentId: departmentId || '',
                                        dateType: date.type,
                                        startTime:
                                            date.range && date.range[0]
                                                ? moment(date.range[0]).format('YYYY-MM-DD')
                                                : '',
                                        endTime:
                                            date.range && date.range[1]
                                                ? moment(date.range[1]).format('YYYY-MM-DD')
                                                : '',
                                        quarter: date?.type === 'quarter' ? date.quarter || 1 : ''
                                    }}
                                >
                                    查看全部排行
                                </LinkTo>
                            }
                        >
                            <TabsList
                                className={styles.clearTabsListPadding}
                                loading={loading.effects['report/fetchJbryph']}
                                activeKey={`${jbryIndex}`}
                                onTabChange={jbryChange}
                                data={[
                                    {
                                        label: '总加班',
                                        content: (
                                            <List
                                                data={report.jbryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 小时</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/overtime',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    },
                                    {
                                        label: '工作日',
                                        content: (
                                            <List
                                                data={report.jbryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 小时</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/overtime',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    },
                                    {
                                        label: '休息日',
                                        content: (
                                            <List
                                                data={report.jbryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 小时</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/overtime',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    },
                                    {
                                        label: '节假日',
                                        content: (
                                            <List
                                                data={report.jbryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 小时</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/overtime',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    }
                                ]}
                            />
                        </Card>
                    </Col>
                </Row>
                <Row gutter={12}>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <KqlxYc data={report.yclxfx} />
                    </Col>
                    <Col className={styles.relative} lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Card
                            bordered={false}
                            className={styles.tabListOverflowY}
                            title={locale('kqycryph')}
                            extra={
                                <LinkTo
                                    to="/office/personnelManagement/attendance/report/reportRank"
                                    query={{
                                        key: 'abnormal',
                                        companyId: companyId || '',
                                        departmentId: departmentId || '',
                                        dateType: date.type,
                                        startTime:
                                            date.range && date.range[0]
                                                ? moment(date.range[0]).format('YYYY-MM-DD')
                                                : '',
                                        endTime:
                                            date.range && date.range[1]
                                                ? moment(date.range[1]).format('YYYY-MM-DD')
                                                : '',
                                        quarter: date?.type === 'quarter' ? date.quarter || 1 : ''
                                    }}
                                >
                                    查看全部排行
                                </LinkTo>
                            }
                        >
                            <TabsList
                                className={styles.clearTabsListPadding}
                                loading={loading.effects['report/fetchYcryph']}
                                activeKey={`${ycryIndex}`}
                                onTabChange={ycryChange}
                                data={[
                                    {
                                        label: '总异常',
                                        content: (
                                            <List
                                                data={report.ycryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 次</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/timetag/attendRecord',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    },
                                    {
                                        label: '迟到',
                                        content: (
                                            <List
                                                data={report.ycryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 次</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/timetag/attendRecord',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    },
                                    {
                                        label: '早退',
                                        content: (
                                            <List
                                                data={report.ycryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 次</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/timetag/attendRecord',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    },
                                    {
                                        label: '缺卡',
                                        content: (
                                            <List
                                                data={report.ycryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 次</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/timetag/attendRecord',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    },
                                    {
                                        label: '缺勤',
                                        content: (
                                            <List
                                                data={report.ycryph}
                                                columns={publicColumns(
                                                    text => (
                                                        <Fragment>
                                                            <span className="oa-number">{text} 次</span>
                                                        </Fragment>
                                                    ),
                                                    '/office/personnelManagement/attendance/timetag/attendRecord',
                                                    getForm()
                                                )}
                                                rowKey={row => row.id}
                                            />
                                        )
                                    }
                                ]}
                            />
                        </Card>
                    </Col>
                </Row>
            </div>
        </div>
    );
};

export default withRoutePage(
    connect(({ report, loading }) => ({
        report,
        loading
    }))(Form.create()(Report))
);
